﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace JYStockAnalyser.DataGeter
{
    public partial class FrmReportGeter : Form
    {
        string beginStockNO;
        string endStockNO;
        int beginYear;
        int beginQuarter;
        int endYear;
        int endQuarter;

        WebBrowser webb1;
        HtmlDocument htmldoc1;
        System.Threading.Thread th;

        public FrmReportGeter()
        {
            InitializeComponent();
            m_enterReadyState();
            Control.CheckForIllegalCrossThreadCalls = false;
            webb1 = new WebBrowser();
            webb1.Navigate("about:blank");
            htmldoc1 = webb1.Document.OpenNew(true);
        }

        private void btnGet_Click(object sender, EventArgs e)
        {
            m_enterGettingState();

            beginStockNO = this.txtBeginStock.Text.Trim();
            endStockNO = this.txtEndStock.Text.Trim();
            try
            {
                beginYear = int.Parse(this.txtBeginYear.Text.Trim());
                beginQuarter = int.Parse(this.txtBeginQuarter.Text.Trim());
                endYear = int.Parse(this.txtEndYear.Text.Trim());
                endQuarter = int.Parse(this.txtEndQuarter.Text.Trim());
            }
            catch (System.FormatException)
            {
                MessageBox.Show("请输入正确的年份和季度");
                m_enterReadyState();
                return;
            }

            if (this.cbReporttype.SelectedIndex == 0)
            {
                th = new System.Threading.Thread(new System.Threading.ThreadStart(m_getData1));
                th.Start();
            }
            else if (this.cbReporttype.SelectedIndex == 1)
            {
                th = new System.Threading.Thread(new System.Threading.ThreadStart(m_getData2));
                th.Start();
            }
            else if (this.cbReporttype.SelectedIndex == 2)
            {
                th = new System.Threading.Thread(new System.Threading.ThreadStart(m_getData3));
                th.Start();
            }
            else if (this.cbReporttype.SelectedIndex == 3)
            {
                th = new System.Threading.Thread(new System.Threading.ThreadStart(m_getData9));
                th.Start();
            }
        }

    

        private void m_getData2_1()
        {
            Dictionary<int, KeyValuePair<int, int>> mappings = new Dictionary<int, KeyValuePair<int, int>>();
            mappings.Add(1, new KeyValuePair<int, int>(92001, 92047));
            mappings.Add(2, new KeyValuePair<int, int>(92025, 92048));
            mappings.Add(3, new KeyValuePair<int, int>(92026, 92049));
            mappings.Add(4, new KeyValuePair<int, int>(92027, 92050));
            mappings.Add(5, new KeyValuePair<int, int>(92028, 92003));
            mappings.Add(6, new KeyValuePair<int, int>(92029, 92051));
            mappings.Add(7, new KeyValuePair<int, int>(92030, 92052));
            mappings.Add(8, new KeyValuePair<int, int>(92031, 92053));
            mappings.Add(9, new KeyValuePair<int, int>(92032, 91008));
            mappings.Add(10, new KeyValuePair<int, int>(92033, 92054));
            mappings.Add(11, new KeyValuePair<int, int>(92034, 92013));
            mappings.Add(12, new KeyValuePair<int, int>(92035, 92055));
            mappings.Add(13, new KeyValuePair<int, int>(92036, 92015));
            mappings.Add(14, new KeyValuePair<int, int>(92037, 92056));
            mappings.Add(15, new KeyValuePair<int, int>(92038, 92057));
            mappings.Add(16, new KeyValuePair<int, int>(92010, 92019));
            mappings.Add(17, new KeyValuePair<int, int>(92039, 92058));
            mappings.Add(18, new KeyValuePair<int, int>(92040, 92059));
            mappings.Add(19, new KeyValuePair<int, int>(92041, 92022));
            mappings.Add(20, new KeyValuePair<int, int>(92042, 92023));
            mappings.Add(21, new KeyValuePair<int, int>(92043, 92024));
            mappings.Add(22, new KeyValuePair<int, int>(92044, 92060));
            mappings.Add(23, new KeyValuePair<int, int>(92045, 92061));
            mappings.Add(24, new KeyValuePair<int, int>(92046, 92062));

            m_getData(mappings, "http://gszx.cninfo.com.cn/gszx/cwzb_lrjqfpb.jsp", 1);

            MessageBox.Show("完成!");

            m_enterReadyState();
        }

        private void m_getData2()
        {
            Dictionary<int, KeyValuePair<int, int>> mappings = new Dictionary<int, KeyValuePair<int, int>>();
            mappings.Add(1, new KeyValuePair<int, int>(92001, 92013));
            mappings.Add(2, new KeyValuePair<int, int>(92002, 92014));
            mappings.Add(3, new KeyValuePair<int, int>(92003, 92015));
            mappings.Add(4, new KeyValuePair<int, int>(92004, 92016));
            mappings.Add(5, new KeyValuePair<int, int>(92005, 92017));
            mappings.Add(6, new KeyValuePair<int, int>(92006, 92018));
            mappings.Add(7, new KeyValuePair<int, int>(92007, 92019));
            mappings.Add(8, new KeyValuePair<int, int>(92008, 92020));
            mappings.Add(9, new KeyValuePair<int, int>(92009, 92021));
            mappings.Add(10, new KeyValuePair<int, int>(92010, 92022));
            mappings.Add(11, new KeyValuePair<int, int>(92011, 92023));
            mappings.Add(12, new KeyValuePair<int, int>(92012, 92024));

            m_getData(mappings, "http://gszx.cninfo.com.cn/gszx/cwzb_lrjqfpb.jsp", 2);


            m_getData2_1();
        }

        private void m_getData3_1()
        {
            Dictionary<int, KeyValuePair<int, int>> mappings = new Dictionary<int, KeyValuePair<int, int>>();
            mappings.Add(1, new KeyValuePair<int, int>(93037, 93011));
            mappings.Add(2, new KeyValuePair<int, int>(93038, 93012));
            mappings.Add(3, new KeyValuePair<int, int>(93039, 93015));
            mappings.Add(4, new KeyValuePair<int, int>(93040, 93016));
            mappings.Add(5, new KeyValuePair<int, int>(93041, 93018));
            mappings.Add(6, new KeyValuePair<int, int>(93042, 93056));
            mappings.Add(7, new KeyValuePair<int, int>(93043, 93017));
            mappings.Add(8, new KeyValuePair<int, int>(93044, 93020));
            mappings.Add(9, new KeyValuePair<int, int>(93001, 93021));
            mappings.Add(10, new KeyValuePair<int, int>(93045, 93022));
            mappings.Add(11, new KeyValuePair<int, int>(93046, 93057));
            mappings.Add(12, new KeyValuePair<int, int>(93047, 93023));
            mappings.Add(13, new KeyValuePair<int, int>(93048, 93058));
            mappings.Add(14, new KeyValuePair<int, int>(93003, 93024));
            mappings.Add(15, new KeyValuePair<int, int>(93004, 93059));
            mappings.Add(16, new KeyValuePair<int, int>(93049, 93026));
            mappings.Add(17, new KeyValuePair<int, int>(93050, 93060));
            mappings.Add(18, new KeyValuePair<int, int>(93051, 93061));
            mappings.Add(19, new KeyValuePair<int, int>(93052, 93029));
            mappings.Add(20, new KeyValuePair<int, int>(93053, 93030));
            mappings.Add(21, new KeyValuePair<int, int>(93054, 93031));
            mappings.Add(22, new KeyValuePair<int, int>(93006, 93032));
            mappings.Add(23, new KeyValuePair<int, int>(93007, 93062));
            mappings.Add(24, new KeyValuePair<int, int>(93008, 93034));
            mappings.Add(25, new KeyValuePair<int, int>(93009, 93063));
            mappings.Add(26, new KeyValuePair<int, int>(93010, 93064));
            mappings.Add(27, new KeyValuePair<int, int>(93055, -1));

             m_getData(mappings, "http://gszx.cninfo.com.cn/gszx/cwzb_xjllb.jsp", 1);

            MessageBox.Show("完成!");

            m_enterReadyState();
        }
        

        private void m_getData3()
        {
            Dictionary<int, KeyValuePair<int, int>> mappings = new Dictionary<int, KeyValuePair<int, int>>();
            mappings.Add(1, new KeyValuePair<int, int>(93001, 93019));
            mappings.Add(2, new KeyValuePair<int, int>(93002, 93020));
            mappings.Add(3, new KeyValuePair<int, int>(93003, 93021));
            mappings.Add(4, new KeyValuePair<int, int>(93004, 93022));
            mappings.Add(5, new KeyValuePair<int, int>(93005, 93023));
            mappings.Add(6, new KeyValuePair<int, int>(93006, 93024));
            mappings.Add(7, new KeyValuePair<int, int>(93007, 93025));
            mappings.Add(8, new KeyValuePair<int, int>(93008, 93026));
            mappings.Add(9, new KeyValuePair<int, int>(93009, 93027));
            mappings.Add(10, new KeyValuePair<int, int>(93010, 93028));
            mappings.Add(11, new KeyValuePair<int, int>(93011, 93029));
            mappings.Add(12, new KeyValuePair<int, int>(93012, 93030));
            mappings.Add(13, new KeyValuePair<int, int>(93013, 93031));
            mappings.Add(14, new KeyValuePair<int, int>(93014, 93032));
            mappings.Add(15, new KeyValuePair<int, int>(93015, 93033));
            mappings.Add(16, new KeyValuePair<int, int>(93016, 93034));
            mappings.Add(17, new KeyValuePair<int, int>(93017, 93035));
            mappings.Add(18, new KeyValuePair<int, int>(93018, 93036));

            m_getData(mappings, "http://gszx.cninfo.com.cn/gszx/cwzb_xjllb.jsp", 2);

            m_getData3_1();
        }

        private void m_getData1_1()
        {
            Dictionary<int, KeyValuePair<int, int>> mappings = new Dictionary<int, KeyValuePair<int, int>>();
            mappings.Add(1, new KeyValuePair<int, int>(91067, 91034));
            mappings.Add(2, new KeyValuePair<int, int>(91001, 91094));
            mappings.Add(3, new KeyValuePair<int, int>(91068, 91095));
            mappings.Add(4, new KeyValuePair<int, int>(91069, 91035));
            mappings.Add(5, new KeyValuePair<int, int>(91070, 91096));
            mappings.Add(6, new KeyValuePair<int, int>(91071, 91097));
            mappings.Add(7, new KeyValuePair<int, int>(91072, 91098));
            mappings.Add(8, new KeyValuePair<int, int>(91073, 91099));
            mappings.Add(9, new KeyValuePair<int, int>(91002, 91100));
            mappings.Add(10, new KeyValuePair<int, int>(91074, 91101));
            mappings.Add(11, new KeyValuePair<int, int>(91075, 91036));
            mappings.Add(12, new KeyValuePair<int, int>(91008, 91102));
            mappings.Add(13, new KeyValuePair<int, int>(91076, 91103));
            mappings.Add(14, new KeyValuePair<int, int>(91077, 91104));
            mappings.Add(15, new KeyValuePair<int, int>(91078, 91105));
            mappings.Add(16, new KeyValuePair<int, int>(91079, 91106));
            mappings.Add(17, new KeyValuePair<int, int>(91080, 91040));
            mappings.Add(18, new KeyValuePair<int, int>(91081, 91041));
            mappings.Add(19, new KeyValuePair<int, int>(91082, 91107));
            mappings.Add(20, new KeyValuePair<int, int>(91083, 91052));
            mappings.Add(21, new KeyValuePair<int, int>(91084, 91108));
            mappings.Add(22, new KeyValuePair<int, int>(91085, 91109));
            mappings.Add(23, new KeyValuePair<int, int>(91086, 91110));
            mappings.Add(24, new KeyValuePair<int, int>(91087, 91111));
            mappings.Add(25, new KeyValuePair<int, int>(91038, 91112));
            mappings.Add(26, new KeyValuePair<int, int>(91005, 91113));
            mappings.Add(27, new KeyValuePair<int, int>(91015, 91114));
            mappings.Add(28, new KeyValuePair<int, int>(91016, 91048));
            mappings.Add(29, new KeyValuePair<int, int>(91018, 91040));
            mappings.Add(30, new KeyValuePair<int, int>(91088, 91115));
            mappings.Add(31, new KeyValuePair<int, int>(91019, 91053));
            mappings.Add(32, new KeyValuePair<int, int>(91010, 91116));
            mappings.Add(33, new KeyValuePair<int, int>(91020, 91117));
            mappings.Add(34, new KeyValuePair<int, int>(91021, 91057));
            mappings.Add(35, new KeyValuePair<int, int>(91026, 91118));
            mappings.Add(36, new KeyValuePair<int, int>(91089, 91119));
            mappings.Add(37, new KeyValuePair<int, int>(91029, 91059));
            mappings.Add(38, new KeyValuePair<int, int>(91023, 91120));
            mappings.Add(39, new KeyValuePair<int, int>(91090, 91061));
            mappings.Add(40, new KeyValuePair<int, int>(91030, 91121));
            mappings.Add(41, new KeyValuePair<int, int>(91092, 91122));
            mappings.Add(42, new KeyValuePair<int, int>(91033, 91064));
            mappings.Add(43, new KeyValuePair<int, int>(91092, 91065));
            mappings.Add(44, new KeyValuePair<int, int>(91093, 91066));

            m_getData(mappings, "http://gszx.cninfo.com.cn/gszx/cwzb_zcfzb.jsp", 1);

            MessageBox.Show("完成!");

            m_enterReadyState();
        }

        private void m_getData1()
        {
            Dictionary<int, KeyValuePair<int, int>> mappings = new Dictionary<int, KeyValuePair<int, int>>();
            mappings.Add(1, new KeyValuePair<int, int>(91001, 91034));
            mappings.Add(2, new KeyValuePair<int, int>(91002, 91035));
            mappings.Add(3, new KeyValuePair<int, int>(91003, 91036));
            mappings.Add(4, new KeyValuePair<int, int>(91004, 91037));
            mappings.Add(5, new KeyValuePair<int, int>(91005, 91038));
            mappings.Add(6, new KeyValuePair<int, int>(91006, 91039));
            mappings.Add(7, new KeyValuePair<int, int>(91007, 91040));
            mappings.Add(8, new KeyValuePair<int, int>(91008, 91041));
            mappings.Add(9, new KeyValuePair<int, int>(91009, 91042));
            mappings.Add(10, new KeyValuePair<int, int>(91010, 91043));
            mappings.Add(11, new KeyValuePair<int, int>(91011, 91044));
            mappings.Add(12, new KeyValuePair<int, int>(91012, 91045));
            mappings.Add(13, new KeyValuePair<int, int>(91013, 91046));
            mappings.Add(14, new KeyValuePair<int, int>(91014, 91047));
            mappings.Add(15, new KeyValuePair<int, int>(91015, 91048));
            mappings.Add(16, new KeyValuePair<int, int>(91016, 91049));
            mappings.Add(17, new KeyValuePair<int, int>(91017, 91050));
            mappings.Add(18, new KeyValuePair<int, int>(91018, 91051));
            mappings.Add(19, new KeyValuePair<int, int>(91019, 91052));
            mappings.Add(20, new KeyValuePair<int, int>(91020, 91053));
            mappings.Add(21, new KeyValuePair<int, int>(91021, 91054));
            mappings.Add(22, new KeyValuePair<int, int>(91022, 91055));
            mappings.Add(23, new KeyValuePair<int, int>(91023, 91056));
            mappings.Add(24, new KeyValuePair<int, int>(91024, 91057));
            mappings.Add(25, new KeyValuePair<int, int>(91025, 91058));
            mappings.Add(26, new KeyValuePair<int, int>(91026, 91059));
            mappings.Add(27, new KeyValuePair<int, int>(91027, 91060));
            mappings.Add(28, new KeyValuePair<int, int>(91028, 91061));
            mappings.Add(29, new KeyValuePair<int, int>(91029, 91062));
            mappings.Add(30, new KeyValuePair<int, int>(91030, 91063));
            mappings.Add(31, new KeyValuePair<int, int>(91031, 91064));
            mappings.Add(32, new KeyValuePair<int, int>(91032, 91065));
            mappings.Add(33, new KeyValuePair<int, int>(91033, 91066));

            m_getData(mappings, "http://gszx.cninfo.com.cn/gszx/cwzb_zcfzb.jsp", 2);

            m_getData1_1();
        }

        private void m_getData(Dictionary<int, KeyValuePair<int, int>> mappings, string address, int stockType)
        {
            string[] stocks = DataTool.GetAllStocks(beginStockNO, endStockNO, stockType);

            foreach (string stock in stocks)
            {
                for (int year = beginYear; year <= endYear; year++)
                {
                    for (int quarter = 1; quarter <= 4; quarter++)
                    {
                        string strWebContent = m_getWebContent(stock, year, quarter,  address);
                        
                        int start1 = strWebContent.IndexOf("<table width=\"100%\" border=\"0\" cellspacing=1 cellpadding=\"4\">");

                        if (start1 == -1)
                        {
                            if (strWebContent.Contains("该页无法显示"))
                            {
                                quarter -= 1;
                                continue;
                            }
                            System.IO.StreamWriter sw = new StreamWriter(@"log.txt", true);
                            sw.WriteLine("=====================================");
                            sw.WriteLine(stock + "   " + year.ToString() + "   " + quarter.ToString());
                            sw.WriteLine("--------------");
                            sw.WriteLine(strWebContent.ToString());
                            sw.WriteLine("=====================================");
                            sw.Close();
                            continue;
                        }

                        int end1 = strWebContent.IndexOf("</table>", start1 + 100);

                        string content1 = strWebContent.Substring(start1, end1 - start1 + 8);
                        htmldoc1.OpenNew(true);
                        htmldoc1.Write(content1);

                        HtmlElementCollection trs = htmldoc1.GetElementsByTagName("TR");

                        for (int i = 1; i <= mappings.Count; i++)
                        {
                            DataTool.InsertGuideLine(stock, mappings[i].Key, year, quarter, GetValue(trs[i].GetElementsByTagName("TD")[1].InnerText));
                            if (mappings[i].Value != -1)
                            {
                                DataTool.InsertGuideLine(stock, mappings[i].Value, year, quarter, GetValue(trs[i].GetElementsByTagName("TD")[3].InnerText));
                            }
                        }

                        lbStatus.Items.Add(string.Format("stock : {0}    year : {1}    quarter : {2}", stock, year, quarter));
                        lbStatus.SelectedIndex = lbStatus.Items.Count - 1;
                    }
                }
            }
        }

        private string m_getWebContent(string stock, int year, int quarter, string address)
        {
            string yyyy = year.ToString();
            string mm = string.Empty;
            if (quarter == 1) { mm = "-03-31"; }
            if (quarter == 2) { mm = "-06-30"; }
            if (quarter == 3) { mm = "-09-30"; }
            if (quarter == 4) { mm = "-12-31"; }

            string stockCode = stock;

            ASCIIEncoding encoding = new ASCIIEncoding();
            string postData = "yyyy=" + yyyy;
            postData += ("&mm=" + mm);
            postData += ("&stockCode=" + stockCode);
            byte[] data = encoding.GetBytes(postData);

            bool success = false;
            string content = string.Empty;
            while (!success)
            {
                try
                {
                    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(address);

                    myRequest.Method = "POST";
                    myRequest.ContentType = "application/x-www-form-urlencoded";
                    myRequest.ContentLength = data.Length;
                    Stream newStream = myRequest.GetRequestStream();

                    newStream.Write(data, 0, data.Length);
                    newStream.Close();

                    HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                    StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.Default);
                    content = reader.ReadToEnd();
                    success = true;
                }
                catch
                {
                    System.Threading.Thread.Sleep(5000);
                }
            }
            return content;
        }

        private List<string> m_getStocks()
        {
            List<string> stockNOs = new List<string>();
            string[] stocks1 = DataTool.GetAllStocks(beginStockNO, endStockNO, 1);
            string[] stocks2 = DataTool.GetAllStocks(beginStockNO, endStockNO, 2);

            stockNOs.AddRange(stocks1);
            stockNOs.AddRange(stocks2);

            return stockNOs;
        }

        private void m_enterReadyState()
        {
            this.btnStop.Enabled = false;
            this.btnGet.Enabled = true;
            this.txtBeginStock.Enabled = true;
            this.txtBeginQuarter.Enabled = true;
            this.txtBeginYear.Enabled = true;
            this.txtEndStock.Enabled = true;
            this.txtEndYear.Enabled = true;
            this.txtEndQuarter.Enabled = true;
            this.cbReporttype.Enabled = true;
        }

        private void m_enterGettingState()
        {
            this.btnStop.Enabled = true;
            this.btnGet.Enabled = false;
            this.txtBeginStock.Enabled = false;
            this.txtBeginYear.Enabled = false;
            this.txtBeginQuarter.Enabled = false;
            this.txtEndStock.Enabled = false;
            this.txtEndYear.Enabled = false;
            this.txtEndQuarter.Enabled = false;
            this.cbReporttype.Enabled = false;    
        }

        private decimal GetValue(string str)
        {
            decimal v = -77777.77m;
            try
            {
                v = decimal.Parse(str.Trim());

            }
            catch (Exception)
            {
            }
            return v;
        }

        private void label8_Click(object sender, EventArgs e)
        {

        }


        private void m_getData9()
        {
            List<string> stockNOs = new List<string>();
            string[] stocks1 = DataTool.GetAllStocks(beginStockNO, endStockNO, 1);
            string[] stocks2 = DataTool.GetAllStocks(beginStockNO, endStockNO, 2);

            stockNOs.AddRange(stocks1);
            stockNOs.AddRange(stocks2);

            foreach (string stock in stockNOs)
            {
                string strWebContent = string.Empty;
                bool pass = true;
                do
                {
                    strWebContent = Tool.GetContentFromUrll(String.Format("http://stockdata.stock.hexun.com/finance_default_{0}.shtml", stock));
                    int start1 = strWebContent.IndexOf("<table width=\"603\" border=\"0\" cellspacing=\"1\" cellpadding=\"0\" bgcolor=\"#CDCED0\" style=\"margin-top:10px\">", StringComparison.OrdinalIgnoreCase);
                    if (start1 == -1)
                    {
                        if (strWebContent.Contains("该页无法显示"))
                        {
                            pass = false;
                        }
                        else
                        {
                            continue;
                        }
                    }
                    int end1 = strWebContent.IndexOf("</table>", start1 + 1000);
                    string content1 = strWebContent.Substring(start1, end1 - start1 + 8);
                    htmldoc1.OpenNew(true);
                    htmldoc1.Write(content1);
                } while (!pass);
               

                HtmlElementCollection trs = htmldoc1.GetElementsByTagName("TR");

                for (int i = 1; i < trs.Count; i++)
                {
                    HtmlElementCollection tds = trs[i].GetElementsByTagName("TD");
                    string quarterString = tds[0].InnerText;

                    int year = int.Parse(quarterString.Substring(0, 2)) + 2000;
                    int quarter = 1;

                    if (quarterString.IndexOf("第1季") != -1)
                    {
                        quarter = 1;
                    }
                    else if (quarterString.IndexOf("中期") != -1)
                    {
                        quarter = 2;
                    }
                    else if (quarterString.IndexOf("前3季") != -1)
                    {
                        quarter = 3;
                    }
                    else if (quarterString.IndexOf("年度") != -1)
                    {
                        quarter = 4;
                    }

                    for (int j = 1; j < 10; j++)
                    {
                        string str = tds[j].InnerText;
                        str = (str == null ? null : str.Trim().Replace("%", ""));
                        decimal v = -77777.77m;
                        if (!string.IsNullOrEmpty(str))
                        {
                            try
                            {
                                v = decimal.Parse(str);
                            }
                            catch (System.FormatException)
                            {
                                Console.WriteLine("error string : " + str);
                            }
                        }

                        DataTool.InsertGuideLine(stock, 9000 + j, year, quarter, v);
                        lbStatus.Items.Add(String.Format("stock : {0}", stock));
                        lbStatus.SelectedIndex = lbStatus.Items.Count - 1;
                    }
                }

            }
        }
    }
}
